package de.pa2.proxy;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import de.pa2.proxy.config.ServerConfiguration;
import de.pa2.templates.VelocityHelper;
import de.pa2.templates.VelocityTool;

public class ProxyPacHttpRequestHandler implements HttpRequestHandler {
	private ServerConfiguration configuration = null;

	public ProxyPacHttpRequestHandler(ServerConfiguration configuration) {
		super();
		this.configuration = configuration;
	}

	public void handle(HttpRequest request, HttpResponse response,
			HttpContext context) throws HttpException, IOException {
		// TODO fix static path
		final String template = "/var/work/projects/rathaus21/proxy/src/templates/ProxyPac.vm";
		response.setHeader("Content-Type", "application/x-javascript-config");
//		response.setHeader("Content-Type", "text/plain");
		
		final VelocityContext ctx = new VelocityContext();
		VelocityTool tool = new VelocityTool(template);

		Header hostHeader = request.getFirstHeader("Host");
		if (hostHeader != null) {
			//TODO check!
			String[] tmp = hostHeader.getValue().split(":");
			ctx.put("host", tmp[0]);
			tool.add("host", tmp[0]);
			ctx.put("port", tmp[1]);
			tool.add("port", tmp[1]);
		}

		ctx.put("configuration", configuration);
		tool.add("configuration", configuration);
		ctx.put("tool", tool);

		EntityTemplate body = new EntityTemplate(new ContentProducer() {

			public void writeTo(final OutputStream outstream)
					throws IOException {
				OutputStreamWriter writer = new OutputStreamWriter(outstream,
						"UTF-8");
				Template tpl;
				try {
					tpl = VelocityHelper.getEngine().getTemplate(template);
					tpl.merge(ctx, writer);
				} catch (ResourceNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				writer.flush();
			}

		});
		body.setContentType("text/html; charset=UTF-8");
		response.setEntity(body);
	}

}
